<template>
  <div class="equipment">
    <div id="container"></div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { getequipmentlist, getTitle } from '@/api/echarts';

let map = null;
let distCluster = null;
let pointSimplifierIns = null;

export default {
  name: 'index',
  props: {
    showPoints: {
      type: Boolean,
      default: true, // 默认显示点
    },
  },
  data() {
    return {
      lat: null,
      lng: null,
      zoom: 5, // 地图默认缩放级别
      pointsData: [], // 存储所有点数据
    };
  },
  mounted() {
    this.initMap();  // 初始化地图
  },
  watch: {
    showPoints(newValue) {
      // 当 showPoints 发生变化时，显示或隐藏点坐标
      if (newValue) {
        this.showPointCoordinates();
      } else {
        this.hidePointCoordinates();
      }
    },
  },
  methods: {
    async fetchlnglat() {
      try {
        const title = await getTitle();
        this.lat = parseFloat(title.msg.lat);
        this.lng = parseFloat(title.msg.lng);
        this.zoom = title.msg.zoom;

        // 检查经纬度是否有效，并更新地图中心和缩放级别
        if (!isNaN(this.lat) && !isNaN(this.lng) && map) {
          map.setCenter([this.lng, this.lat]);
          map.setZoom(this.zoom);
        } else {
          console.error('无效的经纬度:', this.lat, this.lng, this.zoom);
        }
      } catch (error) {
        console.error('Error fetching title:', error);
      }
    },

    initMap() {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c", // 高德地图 API Key
        version: "2.0",
        plugins: ['AMap.Scale', 'AMap.Marker', 'AMap.InfoWindow', 'AMap.MarkerCluster'],
        AMapUI: {
          version: '1.1',
          plugins: ['overlay/SimpleMarker']
        }
      }).then((AMap) => {
        map = new AMap.Map("container", {
          viewMode: "2D",
          terrain: false,
          zoom: this.zoom, // 默认缩放
          center: [116.397428, 39.90923], // 默认中心点
          mapStyle: 'amap://styles/blue', // 地图样式
        });

        // 设置地图的边界，防止超出范围
        const bounds = new AMap.Bounds(
          new AMap.LngLat(73.502355, 3.837031), // 西南角
          new AMap.LngLat(135.09567, 53.563624) // 东北角
        );
        map.setLimitBounds(bounds);

        this.aMapUiLoad();  // 确保地图 UI 组件加载完成
      }).catch(e => {
        console.log(`高德地图加载错误提示: ${e}`);
      });
    },

    initPage(DistrictCluster, PointSimplifier, utils) {
      function MyRender(distClusterIns, opts) {
        MyRender.__super__.constructor.apply(this, arguments);
      }

      // 继承和扩展渲染器
      utils.inherit(MyRender, DistrictCluster.Render.Default);
      utils.extend(MyRender.prototype, {
        drawFeaturePolygons: function (ctx, polygons, styleOptions, feature, dataItems) {
          MyRender.__super__.drawFeaturePolygons.apply(this, arguments);
          if (dataItems.length > 0) {
            this.drawMyLabel(feature, dataItems);
          }
        },
        _initContainter: function () {
          MyRender.__super__._initContainter.apply(this, arguments);
          this._createCanvas('mylabel', this._container);
        },
        drawMyLabel: function (feature, dataItems) {
          var pixelRatio = this.getPixelRatio();
          var containerPos = map.lngLatToContainer(feature.properties.centroid || feature.properties.center);
          var labelCtx = this._getCanvasCxt('mylabel');
          var centerX = containerPos.getX() * pixelRatio,
              centerY = containerPos.getY() * pixelRatio;

          var name = feature.properties.name;
          var count = ' (' + dataItems.length + ')';
          
          labelCtx.font = 14 * pixelRatio + 'px 微软雅黑';
          var nameMetrics = labelCtx.measureText(name);
          var countMetrics = labelCtx.measureText(count);
          var totalWidth = nameMetrics.width + countMetrics.width;

          var halfTxtWidth = totalWidth / 2;

          // 计算背景矩形的尺寸
          var rectWidth = totalWidth + 12 * pixelRatio; // 增加内边距
          var rectHeight = 22 * pixelRatio;
          var rectX = centerX - halfTxtWidth - 6 * pixelRatio;
          var rectY = centerY - rectHeight / 2;
          var cornerRadius = 5 * pixelRatio;

          // 绘制圆角矩形背景
          labelCtx.save();
          labelCtx.beginPath();
          labelCtx.moveTo(rectX + cornerRadius, rectY);
          labelCtx.lineTo(rectX + rectWidth - cornerRadius, rectY);
          labelCtx.quadraticCurveTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + cornerRadius);
          labelCtx.lineTo(rectX + rectWidth, rectY + rectHeight - cornerRadius);
          labelCtx.quadraticCurveTo(rectX + rectWidth, rectY + rectHeight, rectX + rectWidth - cornerRadius, rectY + rectHeight);
          labelCtx.lineTo(rectX + cornerRadius, rectY + rectHeight);
          labelCtx.quadraticCurveTo(rectX, rectY + rectHeight, rectX, rectY + rectHeight - cornerRadius);
          labelCtx.lineTo(rectX, rectY + cornerRadius);
          labelCtx.quadraticCurveTo(rectX, rectY, rectX + cornerRadius, rectY);
          labelCtx.closePath();

          // 设置背景颜色
          if (feature.properties.level === 'province') {
            labelCtx.fillStyle = '#ADD8E6'; // 浅蓝色背景
          } else if (feature.properties.level === 'district') {
            labelCtx.fillStyle = '#DDA0DD'; // 浅紫色背景
          } else {
            labelCtx.fillStyle = '#FFFFE0'; // 默认背景颜色
          }
          labelCtx.fill();

          // 绘制文本
          labelCtx.fillStyle = '#000000'; // 黑色文本
          labelCtx.textBaseline = 'middle';
          labelCtx.fillText(name, centerX - halfTxtWidth, centerY);

          // 绘制加粗的数字部分
          labelCtx.font = 'bold ' + 14 * pixelRatio + 'px 微软雅黑';
          labelCtx.fillText(count, centerX - halfTxtWidth + nameMetrics.width, centerY);

          labelCtx.restore();
        }
      });

      // 初始化点简化器和区域聚合
      pointSimplifierIns = new PointSimplifier({
        map: map,
        autoSetFitView: false,
        zIndex: 110,
        getPosition: function (item) {
          if (!item || !item.lnglat || isNaN(item.lnglat[0]) || isNaN(item.lnglat[1])) {
            return '';
          }
          return item.lnglat;
        },
        getHoverTitle: function (dataItem, idx) {
          return `<div style="height: 12vh;width: 16vw;background-color:#FFFFFF;margin:0;padding:0;z-index:9999999">
            <h2>第${idx+1}台设备</h2>
            <p>${dataItem.detail}</p>
          </div>`;
        },
        renderOptions: {
          pointStyle: {
            width: 6,
            height: 6,
            fillStyle: 'rgba(153, 0, 153, 0.38)' // 点的颜色样式
          },
          hoverTitleStyle: {
            position: 'top'
          }
        }
      });

      distCluster = new DistrictCluster({
        zIndex: 100,
        map: map,
        autoSetFitView: false,
        getPosition: function (item) {
          if (!item || !item.lnglat || isNaN(item.lnglat[0]) || isNaN(item.lnglat[1])) {
            return null;
          }
          return item.lnglat;
        },
        renderConstructor: MyRender,
        renderOptions: {
          featureClickToShowSub: true,
          featureStyle: {
            fillStyle: 'rgba(192,192,192,0.5)',
            strokeStyle: 'rgba(0,0,0,0.5)',
            lineWidth: 1,
            hoverOptions: {
              fillStyle: 'rgba(255,255,255,0.01)',
              strokeStyle: '#ffa500',
              lineWidth: 2,
            }
          }
        }
      });

      // 监听点击事件，显示更多信息
      distCluster.on('featureClick', function (e, feature) {
        console.log('点击了:', feature);
      });

      this.getEquipmentList();  // 初始化设备数据加载
    },

    aMapUiLoad() {
      AMapUI.loadUI(['geo/DistrictCluster', 'simplifier/PointSimplifier', 'util'], (DistrictCluster, PointSimplifier, utils) => {
        this.initPage(DistrictCluster, PointSimplifier, utils);
      });
    },

    async getEquipmentList() {
      try {
        const res = await getequipmentlist();
        this.pointsData = res.data.map(equipment => ({
          lnglat: [parseFloat(equipment.lat), parseFloat(equipment.lng)],
          detail: equipment.title,
        }));

        // 加载数据到聚合器中
        if (distCluster) {
          distCluster.setData(this.pointsData);
        }

        if (pointSimplifierIns) {
          pointSimplifierIns.setData(this.pointsData);
        }

      } catch (error) {
        console.error('获取设备列表失败:', error);
      }
    },

    showPointCoordinates() {
      if (pointSimplifierIns) {
        pointSimplifierIns.show();
      }
    },

    hidePointCoordinates() {
      if (pointSimplifierIns) {
        pointSimplifierIns.hide();
      }
    }
  }
};
</script>

<style scoped>
#container {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
}
</style>
